package com.example.browser;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class setting extends Activity {
    private static final String FILENAME = "YX";
    private String getvideo,openApp,prefix,vtb,htb;
    String androidId;
    private Boolean isUser=true;
    private List<Map<String, String>> list =
            new ArrayList<Map<String, String>>(); 		// 保存所有的List数据

    private List<Map<String, String>> list2 =
            new ArrayList<Map<String, String>>();
    private SimpleAdapter simpleAdapter = null;
    private SimpleAdapter simpleAdapter2 = null; // 适配器
    private ListView datalist = null ;				// 定义ListView
    private ListView datalist2 = null ;

    private MyDatabaseHelper dbHelper;
    int id; //按值查找id
    SharedPreferences share;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);

        intclick();
        share=getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);

        queryinfo();
       /* //网络属于耗时操作 需要多线程来运行 否则会异常
        androidId = Settings.System.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        new Thread(new Runnable(){
            public void run(){
                //获取服务端的url
                try {
                    String htmlString=CodeHtml.GetHtml("", "utf-8");
                    //System.out.println(htmlString);
//                   //https://blog.csdn.net/Bingxuebojue/article/details/118899698
//                    // 正则表达式，截取照片_ 与 _ 中间的字符串
//                    String regex = "密(.*)密";
//                    String fileName= htmlString;
//                    Pattern pattern = Pattern.compile(regex);
//                    Matcher matcher = pattern.matcher(fileName);
//                    while(matcher.find()){
//                        // 打印中间字符
//                        System.out.println(matcher.group(1));
//                    }
                    if (htmlString.contains(androidId)){
                        isUser=true;
                    }else
                        isUser=false;
                }catch(Exception e){
                    System.err.println("错误");
                }
            }
        }).start();*/
        this.datalist2.setOnItemClickListener(new OnItemClickListenerImpl2()) ;
        this.datalist.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            SharedPreferences.Editor edit=share.edit();
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                switch (position){
                    case 0:
                        Intent intent = new Intent(setting.this,jstool.class);
                        startActivity(intent);
                        break;
                    case 1:
                        if(share.getString("getvideo", "自动嗅探视频【关闭】").equals("自动嗅探视频【关闭】")){
                            edit.putString("getvideo","自动嗅探视频【开启】");
                            edit.commit();
                            Toast.makeText(setting.this, "开启成功，这个功能会自动爬取网页视频资源，点击网页底部视频按钮可查看", Toast.LENGTH_SHORT).show();

                        }else if(share.getString("getvideo", "自动嗅探视频【关闭】").equals("自动嗅探视频【开启】")){
                            edit.putString("getvideo","自动嗅探视频【关闭】");
                            edit.commit();
                            Toast.makeText(setting.this, "关闭成功", Toast.LENGTH_SHORT).show();
                        }
                        list.clear();
                        list2.clear();
                        queryinfo();
                        break;
                    case 2:
                        if(share.getString("openApp", "允许网站打开app【关闭】").equals("允许网站打开app【开启】")){
                            edit.putString("openApp", "允许网站打开app【关闭】");
                            edit.commit();
                            Toast.makeText(setting.this, "关闭成功", Toast.LENGTH_SHORT).show();
                        } else if(share.getString("openApp", "允许网站打开app【关闭】").equals("允许网站打开app【关闭】")) {
                            edit.putString("openApp", "允许网站打开app【开启】");
                            edit.commit();
                            Toast.makeText(setting.this, "开启成功，会让网页打开app，但是爱奇艺这些会疯狂提醒", Toast.LENGTH_SHORT).show();
                        }
                        list.clear();
                        list2.clear();
                        queryinfo();
                        break;
                    case 3:
                        if(share.getString("prefix", "自动前缀【关闭】").equals("自动前缀【关闭】")){
                            edit.putString("prefix", "自动前缀【开启】");
                            edit.commit();
                            Toast.makeText(setting.this, "开启成功，这个主要功能是为了破解vip视频", Toast.LENGTH_SHORT).show();
                        } else if(share.getString("prefix", "自动前缀【关闭】").equals("自动前缀【开启】")) {
                            edit.putString("prefix", "自动前缀【关闭】");
                            edit.commit();
                            Toast.makeText(setting.this, "关闭成功", Toast.LENGTH_SHORT).show();
                        }
                        list.clear();
                        list2.clear();
                        queryinfo();
                        break;
                    case 4:
                        if(share.getString("vtb", "滑动时隐藏上下部分【关闭】").equals("滑动时隐藏上下部分【关闭】")){
                            edit.putString("vtb", "滑动时隐藏上下部分【开启】");
                            edit.commit();
                            Toast.makeText(setting.this, "开启成功，如果滑动时卡死或者网页反应慢请关闭", Toast.LENGTH_SHORT).show();
                        } else if(share.getString("vtb", "滑动时隐藏上下部分【关闭】").equals("滑动时隐藏上下部分【开启】")) {
                            edit.putString("vtb", "滑动时隐藏上下部分【关闭】");
                            edit.commit();
                            Toast.makeText(setting.this, "关闭成功", Toast.LENGTH_SHORT).show();
                        }
                        list.clear();
                        list2.clear();
                        queryinfo();
                        break;
                    case 5:
                        if(share.getString("htb", "左右滑动网页前进后退【关闭】").equals("左右滑动网页前进后退【关闭】")){
                            edit.putString("htb", "左右滑动网页前进后退【开启】");
                            edit.commit();
                            Toast.makeText(setting.this, "开启成功，如果滑动时干扰到网页请关闭", Toast.LENGTH_SHORT).show();
                        } else if(share.getString("htb", "左右滑动网页前进后退【关闭】").equals("左右滑动网页前进后退【开启】")) {
                            edit.putString("htb", "左右滑动网页前进后退【关闭】");
                            edit.commit();
                            Toast.makeText(setting.this, "关闭成功", Toast.LENGTH_SHORT).show();
                        }
                        list.clear();
                        list2.clear();
                        queryinfo();
                        break;
                }
            }
        }) ;
    }
    private void queryinfo(){
        vtb=share.getString("vtb", "滑动时隐藏上下部分【关闭】");
        htb=share.getString("htb", "左右滑动网页前进后退【关闭】");
        openApp=share.getString("openApp", "允许网站打开app【关闭】");
        getvideo=share.getString("getvideo", "自动嗅探视频【关闭】");
        prefix=share.getString("prefix", "自动前缀【关闭】");
        String data[] = new String[] {"脚本管理",getvideo,openApp,prefix,vtb,htb,"清空历史记录","清空搜索记录","导出书签"}; 	// 定义显示的数据
        this.datalist =(ListView) super.findViewById(R.id.datalist) ;	// 取得组件
        this.datalist2 = (ListView) super.findViewById(R.id.datalist2) ;	// 取得组件
        for (int x = 0; x < 6; x++) {			// 循环设置数据
            Map<String, String> map = new HashMap<String, String>();	// 定义Map集合
            map.put("select", data[x]); 			// 设置_id组件显示数据
            map.put("go", String.valueOf(R.drawable.go1));
            this.list.add(map); 			// 增加数据
        }
        for (int x = 6; x < 9; x++) {			// 循环设置数据
            Map<String, String> map2 = new HashMap<String, String>();	// 定义Map集合
            map2.put("select2", data[x]); 			// 设置_id组件显示数据
            map2.put("go2", String.valueOf(R.drawable.go1));
            this.list2.add(map2); 			// 增加数据
        }
        this.simpleAdapter = new SimpleAdapter(this, 		// 实例化SimpleAdapter
                this.list,			// 要包装的数据集合
                R.layout.settingszujian, 		// 要使用的显示模板
                new String[] { "select", "go" }, 	// 定义要显示的Map的Key
                new int[] {R.id.select, R.id.go});	// 与模板中的组件匹配
        this.datalist.setAdapter(this.simpleAdapter) ;		// 设置显示数据
        this.simpleAdapter2 = new SimpleAdapter(this, 		// 实例化SimpleAdapter
                this.list2,			// 要包装的数据集合
                R.layout.settingszujian, 		// 要使用的显示模板
                new String[] { "select2", "go2" }, 	// 定义要显示的Map的Key
                new int[] {R.id.select, R.id.go});	// 与模板中的组件匹配
        this.datalist2.setAdapter(this.simpleAdapter2) ;		// 设置显示数据
    }
    private void intclick() {


    }


    //ListView和ScrollView冲突 https://www.cnblogs.com/changyiqiang/p/5752779.html


    private class OnItemClickListenerImpl2 implements AdapterView.OnItemClickListener {

        SharedPreferences.Editor edit=share.edit();
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            Map<String,String> map2 = (Map<String,String>) setting
                    .this.simpleAdapter2.getItem(position) ;		// 取得列表项
            //String _id = map.get("_id") ;			// 取得Key为_id的内容
            switch (position){
                case 0:
                    delete_all_dialog("historyDB");
                    break;
                case 1:
                    delete_all_dialog("search_hisDB");
                    break;
                case 2:
                    save();

                    break;
            }


        }
    }
    //复制数据库https://blog.csdn.net/wuhongqi0012/article/details/17222053
    public void save() {
        @SuppressLint("SdCardPath") String dbpath = "/data/data/com.zjyzhj.dmbrowser/databases/"
                +"dmbrowser.db";
        boolean success=copyFile(dbpath, Environment.getExternalStorageDirectory().getAbsolutePath() + "/dmbrowser/"
                + "dmbrowser.db");
        if (success){
            Toast.makeText(setting.this, "已导出到：dmbrowser文件夹下，名为dmbrowser.db", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(setting.this, "导出失败", Toast.LENGTH_SHORT).show();
        }
    }
    public static boolean copyFile(String source, String dest) {
        try {
            File f1 = new File(source);
            File f2 = new File(dest);
            InputStream in = new FileInputStream(f1);

            OutputStream out = new FileOutputStream(f2);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0)
                out.write(buf, 0, len);

            in.close();
            out.close();

        } catch (FileNotFoundException ex) {
            return false;
        } catch (IOException e) {
            return false;
        }

        return true;

    }

    public void delete_all_dialog(String dbname){
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("确定全部删除吗？")//设置对话框的标题
                //设置对话框的按钮
                .setMessage("确定清空")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        delete_all(dbname);

                        dialog.dismiss();
                    }
                }).create();
        dialog.show();

    }
    public void delete_all(String dbname){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from "+dbname, null);
        while (cursor.moveToNext()) {
            id=cursor.getInt(0);
            db.delete(dbname,"id=?",new String[] {String.valueOf(id)});
        }
        cursor.close();
        db.close();
        Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();




    }
}